package liportest.ability;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AbilityServiceImpl implements AbilityService {
    @Autowired
    private StateMachine<AbilityStatus, AbilityChangeEvent> abilityStateMachine;

    @Autowired
    private  StateMachinePersister<AbilityStatus, AbilityChangeEvent, AbilityModel> stateMachinePersister;


    private int id = 1;
    private Map<Integer, AbilityModel> abilityModelMap = new HashMap<>();

    public Map<Integer, AbilityModel> getAbility() {
        return abilityModelMap;
    }



    public AbilityModel createAbility() {
        AbilityModel abilityModel = new AbilityModel();
        abilityModel.setId(id++);
        abilityModel.setAbilityStatus(AbilityStatus.WRITED);
        abilityModelMap.put(abilityModel.getId(), abilityModel);
        return abilityModel;
    }

    public AbilityModel submitApproveAbility(Integer id) {
        final AbilityModel abilityModel = abilityModelMap.get(id);

        Message message = MessageBuilder.withPayload(AbilityChangeEvent.SUBMIT_APPROVE).setHeader("ability", abilityModel).build();

        if (!sendEvent(message,abilityModel)) {
            System.out.println("提交失败");
        }

        return abilityModel;
    }

    private synchronized boolean sendEvent(Message<AbilityChangeEvent> message,AbilityModel abilityModel) {
        boolean result = false;

        try {
            abilityStateMachine.start();
            stateMachinePersister.restore(abilityStateMachine,abilityModel);
            Thread.sleep(1000);
            result = abilityStateMachine.sendEvent(message);
            stateMachinePersister.persist(abilityStateMachine,abilityModel);

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            abilityStateMachine.stop();
        }
        return result;
    }


}
